package com.work.chat.custom.server.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.work.chat.custom.server.config.util.UserUtil;
import com.work.chat.custom.server.pojo.entity.User;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;

@Component
/**
 * 审计字段处理
 */
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private UserUtil userUtil;

    @Override
    public void insertFill(MetaObject metaObject) {
        User  user = userUtil.getUser();
        // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "createBy", () -> ObjectUtils.isEmpty(user.getId())? "system" : user.getId().toString(), String.class);
        this.strictInsertFill(metaObject, "createDate", () -> new Timestamp(System.currentTimeMillis()), Timestamp.class);
        this.strictInsertFill(metaObject, "lastUpdateBy", () -> ObjectUtils.isEmpty(user.getId())? "system" : user.getId().toString(), String.class);
        this.strictUpdateFill(metaObject, "lastUpdateDate", () -> new Timestamp(System.currentTimeMillis()), Timestamp.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        User  user = userUtil.getUser();
        this.strictInsertFill(metaObject, "lastUpdateBy", () -> ObjectUtils.isEmpty(user.getId())? "system" : user.getId().toString(), String.class);
        this.strictUpdateFill(metaObject, "lastUpdateDate", () -> new Timestamp(System.currentTimeMillis()), Timestamp.class);
    }
}